package cloudagent;

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.Date;

public class JavaShellUtil {

	private static final String basePath = "/tmp/";
	
	
	private static final String executeShellLogFile = basePath + "executeShell.log";
	
	

	
	public int executeShell(String shellCommand) throws IOException 
	{
		
		int success = 0;
		
		StringBuffer stringBuffer = new StringBuffer();
		
		BufferedReader bufferedReader = null;
		
		
		
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");
		
		
		try 
		{
			
			stringBuffer.append(dateFormat.format(new Date())).append("׼��ִ��Shell���� ").append(shellCommand).append(" \r\n");
			
			
			Process pid = null;
			
			String[] cmd = {"/bin/sh", "-c", shellCommand};
			
					
			pid = Runtime.getRuntime().exec(cmd);
			//String errorMsg = readInputStream(pid.getErrorStream());
			//String outoutMsg = readInputStream(pid.getInputStream());
			
			if (pid != null) 
			{
				
				stringBuffer.append("��̺ţ�").append(pid.toString()).append("\r\n");
				
				//bufferedReader���ڶ�ȡShell��������� 
				bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
				
				//pid.waitFor();
				
			} 
			else 
			{
				
				stringBuffer.append("û��pid\r\n");
				
			}
			
			
		} 
		catch (Exception ioe) 
		{
			
			stringBuffer.append("ִ��Shell����ʱ�����쳣��\r\n").append(ioe.getMessage()).append("\r\n");
			
		} 
		finally 
		{
			
			if (bufferedReader != null) 
			{
				
				OutputStreamWriter outputStreamWriter = null;
				
				try 
				{
					
					bufferedReader.close();
					
										
					//OutputStream outputStream = new FileOutputStream(executeShellLogFile);
					
					//outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
					
					//outputStreamWriter.write(stringBuffer.toString());
					
				} 
				catch (Exception e) 
				{
					
					e.printStackTrace();
					
				} 
				finally 
				{
					
					//outputStreamWriter.close();
					
				}
				
			}
			
			success = 1;
			
		}
		
		return success;
		
	}

}
